<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class productController extends Controller {

    

    public function __construct($model, $action) {
        parent::__construct($model, $action);
        $this->_setModel('product');
    }

    public function index() {
        $this->_setView("index");
        return $this->_view->output();
    }

    public function getProductDetail($id) {
        return $this->_productModel->getProductbyId($id);
    }

    public function getPeopleDetail($id) {
        return $this->_peopleModel->getPeoplebByUsername($id);
    }

    public function getImageDetail($id) {
        return $this->_imageModel->getImageById($id);
    }

    public function getHighestPriceProduct($id) {
        return $this->_productModel->getHighestPrice($id);
    }

    public function getAllTransactionByProductId($id) {
        return $this->_transactionModel->getAllTransactionByIdProduct($id);
    }

    public function getNumberCommentRowsByProductId($id) {
        return $this->_commentModel->getNumberOfRowByProductId($id);
    }

    public function getLinkProfile($idPeople) {
        $data = $this->getPeopleDetail($idPeople);
        return $data['link_profile'];
    }

    public function getDataViewProduct($id) {
        // Check if product was cached
        $productKey = "product" . $id;
        $productValue = '';
        $peopleValue = '';
        $imageValue = '';

        $highestPrice = $this->getHighestPriceProduct($id);

        $dataProduct = array();

        $dataMemcached = $this->_memcached->get($productKey);
        if ($dataMemcached) {
            // echo "ProductController_getDataViewProduct Hit Data Product in Memcached". "<br/>";
            $dataProduct = $dataMemcached;
            $this->_memcached->delete($productKey);
        } else {

            $productValue = $this->getProductDetail($id);
            if ($productValue) {
                $peopleValue = $this->getPeopleDetail($productValue["idPeople"]);
            }
            $imageValue = $this->getImageDetail($id);
            if ($imageValue) {
                $dataProduct = array_merge($productValue, $peopleValue, $imageValue);
            }
            
            else {
                $element = array("link" => NO_IMAGE);
                $dataProduct = array_merge($productValue, $peopleValue, $element);
            }
            $dataProduct["highest_price"] = $highestPrice["value"];

            /*
             *  Set data memcached for productid
             * Example: product1:value
             */

            $this->_memcached->set($productKey, $dataProduct, 900);
        }

        return $dataProduct;
    }

    public function getDataViewTransaction($id) {
        $productTransactionKey = "product" . $id . "_transaction";
        $dataTransaction = array();

        $dataMemcached = $this->_memcached->get($productTransactionKey);
        if ($dataMemcached) {
            // echo "ProductController_getDataViewTransaction Hit Data Transaction in Memcached" . "<br/>";
            $dataTransaction = $dataMemcached;
            $this->_memcached->delete($productTransactionKey);
        } else {
            /*
             *  Set data memcached for productid
             * Example: product1:value
             */
            $datas = $this->getAllTransactionByProductId($id);
            if ($datas) {
                foreach ($datas as $data) {
                    $name = $this->_peopleModel->getDisplayNameById($data["idPeople"]);
                    $display_name = $name["display_name"];
                    $link = $this->getLinkProfile($data["idPeople"]);
                    $element = array(
                        "display_name" => $display_name,
                        "price" => $data["price"],
                        "link" => $link,
                    );
                    array_push($dataTransaction, $element);
                }
            }
            $this->_memcached->set($productTransactionKey, $dataTransaction, 900);
        }
        return $dataTransaction;
    }

    public function getDataProductAuctionAvailable() {
        $dataProductAvailable = array();
        /*
         * Check in Cached 
         * key: productNowData
         */
        $key = "productNowData";
        $this->_memcached->delete("productNowData");
        $dataMemcached = $this->_memcached->get("productNowData");

        if ($dataMemcached) {
            echo "Hit in ProductModel_getDataProductAuctionAvailable Memcached";
            $dataProductAvailable = $dataMemcached;
        } else {
            $productData = $this->_productModel->getOldProduct();
            //

            if ($productData) {
                foreach ($productData as $data) {
                    $imageValue = $this->getImageDetail($data["idProduct"]);
                    $highest = $this->getHighestPriceProduct($data["idProduct"]);
                    $href = "/product/detail/" + $data["idProduct"];

                    $element = array(
                        "name" => $data["name"],
                        "highest_price" => $highest["value"],
                        "link_image" => $imageValue["link"],
                        "href" => $href,
                    );

                    array_push($dataProductAvailable, $element);
                }
                $this->_memcached->set($key, $dataProductAvailable, 86400);
            } else {
                return "Không có sản phẩm hiện tại nào đang đấu giá";
            }
        }
        return $dataProductAvailable;
    }

    public function pagingComment() {

        $dataHTML = '';

        $idProduct = $_POST["idProduct"];
        $numberOfRows = $this->getNumberCommentRowsByProductId($idProduct);
        $numberOfPages = ceil($numberOfRows / NUMBER_PER_PAGE_COMMENT);

        /*
         * Information
         */
        
        
        $page = $_POST['page'];
        $cur_page = $page;
        $page -= 1;
        $previous_btn = true;
        $next_btn = true;
        $first_btn = true;
        $last_btn = true;

        
        
        $dataCommentContents = array();

        // Get in Memcached
        $commentKey = "product" + $idProduct + "comment_page" + $page;
        $dataMemcached = $this->_memcached->get($commentKey);


        if ($dataMemcached) {
            // echo "ProductController_pagingComment Hit in Cached";
            $dataCommentContents = $dataMemcached;
            $this->_memcached->delete($commentKey);
        }

        // Set to Memcached
        else {
            $dataPage = $this->_commentModel->getCommentByPage($idProduct, $page);

            // var_dump($dataPage);

            if (!empty($dataPage)) {
                foreach ($dataPage as $dt) {

                    $name = $this->_peopleModel->getDisplayNameById($dt["idPeople"]);

                    // var_dump($dt);
                    // var_dump($name);
                    $display_name = $name["display_name"];
                    $link = $this->getLinkProfile($dt["idPeople"]);

                    $element = array(
                        "content" => $dt["content"],
                        "display_name" => $display_name,
                        "link" => $link,
                        "time" => $dt["time"]
                    );
                    array_push($dataCommentContents, $element);
                }
                $this->_memcached->set($commentKey, $dataCommentContents, 900);
            }
        }
        /*
         * Parse Comment List to html
         */

        foreach ($dataCommentContents as $Contents) {
            $dataHTML .= "<p> <a href=" . $Contents["link"] . ">" . $Contents["display_name"] . "</a>";
            $dataHTML .= "<span class='time_comment'> vào ngày " . $Contents["time"] . "</span><br/>";
            $dataHTML .= "<span class='show_comment'>" . $Contents["content"] . "</span><br/>";
        }


        if ($cur_page >= 7) {
            $start_loop = $cur_page - 3;
            if ($numberOfPages > $cur_page + 3)
                $end_loop = $cur_page + 3;
            else if ($cur_page <= $numberOfPages && $cur_page > $numberOfPages - 6) {
                $start_loop = $numberOfPages - 6;
                $end_loop = $numberOfPages;
            } else {
                $end_loop = $numberOfPages;
            }
        } else {
            $start_loop = 1;
            if ($numberOfPages > 7)
                $end_loop = 7;
            else
                $end_loop = $numberOfPages;
        }

        $dataHTML .= "<div class='pagination'><ul>";
        // FOR ENABLING THE FIRST BUTTON
        if ($first_btn && $cur_page > 1) {
            $dataHTML .= "<li p='1' class='active'>Bắt đầu</li>";
        } else if ($first_btn) {
            $dataHTML .= "<li p='1' class='inactive'>Bắt đầu</li>";
        }

        // FOR ENABLING THE PREVIOUS BUTTON
        if ($previous_btn && $cur_page > 1) {
            $pre = $cur_page - 1;
            $dataHTML .= "<li p='$pre' class='active'>Trước</li>";
        } else if ($previous_btn) {
            $dataHTML .= "<li class='inactive'>Trước</li>";
        }
        for ($i = $start_loop; $i <= $end_loop; $i++) {

            if ($cur_page == $i)
                $dataHTML .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
            else
                $dataHTML .= "<li p='$i' class='active'>{$i}</li>";
        }

        // TO ENABLE THE NEXT BUTTON
        if ($next_btn && $cur_page < $numberOfPages) {
            $nex = $cur_page + 1;
            $dataHTML .= "<li p='$nex' class='active'>Sau</li>";
        } else if ($next_btn) {
            $dataHTML .= "<li class='inactive'>Sau</li>";
        }

        // TO ENABLE THE END BUTTON
        if ($last_btn && $cur_page < $numberOfPages) {
            $dataHTML .= "<li p='$numberOfPages' class='active'>Trang cuối</li>";
        } else if ($last_btn) {
            $dataHTML .= "<li p='$numberOfPages' class='inactive'>Trang cuối</li>";
        }
        echo $dataHTML;
        exit();
    }

    public function auction() {
        $idProduct = "";
        $price = "";
        $idPeople = "";
        $time = date("Y-m-d");



        if (isset($_POST) and !empty($_POST)) {
            $idProduct = $_POST["idProduct"];
            $price = $_POST["txtPrice"];
            $idPeople = $_POST["idPeople"];
        }

        $highest = $this->getHighestPriceProduct($idProduct);
        $highestPrice = $highest["value"];

        if ($price <= $highestPrice) {
            echo "Giá bạn đặt nhỏ hơn giá hiện tại";
            exit;
        } else {
            $this->_transactionModel->setTime($time);
            $this->_transactionModel->setPrice($price);
            $this->_transactionModel->setidPeople($idPeople);
            $this->_transactionModel->setidProduct($idProduct);
            $this->_transactionModel->storeToDB();
            echo "Đặt giá thành công";
        }
    }

    public function comment() {
        $idProduct = "";
        $content = "";
        $idPeople = "";
        $time = date("Y-m-d");

        if (isset($_POST) and !empty($_POST)) {
            $idProduct = $_POST["idProduct"];
            $content = $_POST["comment_content"];
            $idPeople = $_POST["idPeople"];
        }
        /*
        var_dump($_POST);
        echo "Noi dung binh luan". $content. "<br/>";
        echo "Id Product: ". $idProduct. "<br/>";
        echo "Id People: ". $idPeople. "<br/>";
        */
        
        
        $this->_commentModel->setContent($content);
        $this->_commentModel->setTime($time);
        $this->_commentModel->setidPeople($idPeople);
        $this->_commentModel->setidProduct($idProduct);
        $this->_commentModel->storeToDB();
        echo "Cảm ơn bạn đã gởi bình luận";
    }

    public function detail($id = NULL) {
        // Set view
        // $this->_memcached->delete("header");
        $this->_setView("index");

        $dataProduct = $this->getDataViewProduct($id) or die("Cannot get Product Infor Data");
        $dataTransaction = $this->getDataViewTransaction($id);
        $dataProductAuctionAvailable = $this->getDataProductAuctionAvailable();
        $header = $this->getHeader();
        
       
        
        if (isset($header)) {
            $this->_view->set("header", $header);
        }
        
        // var_dump($url);
        if (isset($dataProduct["idProduct"])) {
            // Return product data for view
            /*
            $this->_view->set("people_link_profile", $dataProduct["link_profile"]);
            $this->_view->set("people_id", $dataProduct["idPeople"]);
            $this->_view->set("people_display_name", $dataProduct["display_name"]);
            $this->_view->set("product_id", $dataProduct["idProduct"]);
            $this->_view->set("product_link", $dataProduct["link"]);
            $this->_view->set("product_name", $dataProduct["name"]);
            $this->_view->set("product_timeStart", $dataProduct["timeStart"]);
            $this->_view->set("product_timeEnd", $dataProduct["timeEnd"]);
            $this->_view->set("product_price", $dataProduct["priceStart"]);
            $this->_view->set("product_highest_price", $dataProduct["highest_price"]);
            $this->_view->set("product_description", $dataProduct["description"]);
             * */
             
            $this->_view->set("product_data", $dataProduct);
        }
        // Return data for History of Transaction
        if ($dataTransaction) {
            $this->_view->set("transaction_product", $dataTransaction);
        }
        // Return data for Data Now Product
        if ($dataProductAuctionAvailable) {
            $this->_view->set("product_auction_available", $dataProductAuctionAvailable);
        }
        return $this->_view->output();
    }

}

?>
